package com.springboot.springbootlogindemo.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.springbootlogindemo.DTO.UserDTO;

import com.springboot.springbootlogindemo.domain.Follow;
import com.springboot.springbootlogindemo.domain.UserInfo;
import com.springboot.springbootlogindemo.mapper.FollowMapper;
import com.springboot.springbootlogindemo.mapper.UserInfoMapper;
import com.springboot.springbootlogindemo.mapper.UserMapper;

import com.springboot.springbootlogindemo.utils.JwtUtil;
import com.springboot.springbootlogindemo.utils.RegexUtils;
import com.springboot.springbootlogindemo.utils.Result;
import com.springboot.springbootlogindemo.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import com.springboot.springbootlogindemo.domain.User;

import com.springboot.springbootlogindemo.service.UserService;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static com.springboot.springbootlogindemo.utils.Constants.RedisConstants.*;
import static com.springboot.springbootlogindemo.utils.Constants.SystemConstants.USER_NICK_NAME_PREFIX;
import static com.springboot.springbootlogindemo.utils.Constants.SystemConstants.USER_PASSWORD_PREFIX;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  implements UserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserInfoMapper userInfoMapper;


    /**
     * 发送短信，并保存到redis，限时30秒
     * @param phone
     * @return
     */
    @Override
    public Result sendCode(String phone) {
        //校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //如果不符合，就返回错误信息
            return Result.error("123","手机号格式错误！");
        }
        //符合那就生成验证码
        String  code = RandomUtil.randomNumbers(6);
        //保存手机号和验证码到redis里面，采用phone作为key，然后验证码为value，然后设置时长
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //发送验证码，这里可以衔接一个阿里云的短信发送服务
        log.info("发送短信验证码成功，验证码："+code);

        return Result.success(code);
    }


    /**
     * 注册并登录，保存token到redis
     * @param phone
     * @param code
     * @return
     */
    @Override
    public Result loginWithRegister(String phone,String code) {
        //校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            //如果不符合，返回错误信息
            return Result.error("123","手机号格式错误！");
        }
        //从redis获取验证码并且校验
        String cacheCode =stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);


        if(cacheCode==null||!cacheCode.equals(code)){
            return Result.error("123","验证码错误");
        }
        //从mysql数据库中获取用户
        //User user=userDao.findByPhone(phone);
        User user=query().eq("phone",phone).one();
        //如果没有用户就创建该用户
        if(user==null){
            user =createUserWithPhone(phone);
        }
        //创建token
        String token = JwtUtil.createToken();

        //为了避免敏感信息泄露，用UserDTO来代替user，把敏感信息去掉
        UserDTO userDTO = BeanUtil.copyProperties(user,UserDTO.class);

        //添加前缀，方便管理
        String tokenKey="login:token:"+token;

        //存入userDTO到redis里面
//        stringRedisTemplate.opsForHash().put(tokenKey,"id",String.valueOf(userDTO.getId()));
//        stringRedisTemplate.opsForHash().put(tokenKey,"phone",userDTO.getPhone());

//        将long类型先转换成string类型，因为在这里redis的hash类型必须为String，而id是long,long和string并不兼容
//        或者采用上面注释掉的方法选择自己填入key，然后主动添加

//        Map<String,Object> userMap =BeanUtil.beanToMap(userDTO,new HashMap<>(),
//                CopyOptions.create()
//                        .setIgnoreNullValue(true)
//                        .setFieldValueEditor((fieldName,fieldValue)->fieldValue.toString()));

        Map<String,Object> userMap= BeanUtil.beanToMap(userDTO);

//        stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
        redisTemplate.opsForHash().putAll(tokenKey,userMap);

        //设置token有效期三十分钟
        redisTemplate.expire(tokenKey,30L,TimeUnit.MINUTES);
        UserHolder.saveUser(userDTO);
        return Result.success(token,"用户登录成功");

    }


    /**
     * 从DB获取信息
     * @return
     */
    @Override
    public Result getUser() {

        Long id= UserHolder.getUser().getId();
        User user = userMapper.selectById(id);
        if(user==null) Result.error("123","用户不存在");

        return Result.success(user);
    }


    /**
     * 注册用户，并初始化个人信息
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {
        User user= new User();

        user.setPhone(phone);

        user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));

        user.setPassword(USER_PASSWORD_PREFIX+RandomUtil.randomString(10));

        save(user);

        UserInfo userInfo=new UserInfo();
        userInfo.setUserId(user.getId());
        userInfoMapper.insert(userInfo);

        return user;
    }

}

